'use strict';
const Service = require('egg').Service;
const {
  ERROR,
  SUCCESS,
} = require('../util/util');
class BlogService extends Service {
  //创建博客
  async create(blog) {
    const {
      ctx,
    } = this;
    try {
      const res = await this.ctx.model.Blog.create(blog);
      return Object.assign({
        data: res,
      }, SUCCESS);
    } catch (error) {
      ctx.status = 500;
      throw (error);
    }
  }
 
  //删除博客 
  async del({
    id,
    user_id,
  }) {
    const blog = await this.ctx.model.Blog.findById(id);
   console.log(blog)
    if (!blog) {
      return Object.assign({
        error_msg: 'blog not found',
      }, ERROR);
    } else if (blog.user_id !== user_id) {
      return Object.assign(ERROR, {
        msg: 'not allowed to delete others blog',
      });
    }
    blog.destroy();
    return SUCCESS;
  }

  //更新博客
  async update({
    id,
    user_id,
    updates,
  }) {
    //1.先找到该条要修改的博客
    const blog = await this.ctx.model.Blog.findById(id);
    //2.如果博客不存在,提示博客不存在
    if (!blog) {
      return Object.assign(ERROR, {
        msg: 'blog not found',
      });
    } 
    //3.如果博客存在,user_id 不相等,表示不是该用户的博客,不允许修改
    else if (blog.user_id !== user_id) {
      return Object.assign(ERROR, {
        msg: 'not allowed to modify others blog',
      });
    }
    //4.更新博客
    blog.update(updates);
    return SUCCESS;
  }
}

module.exports = BlogService;
